# -*- encoding: utf-8 -*-
"""
File Name: alarm_classification
Description:
Author : 'lirui'
date: 2024/2/22
Contact: marjey_lee@163.com
Change Activity:
2024/2/22:
"""
from modules.blk.cmdb.cmdb_service import CMDBService


class AlarmClassifier:
    def __init__(self):
        self.classification_criteria = self._load_classification_criteria()

    def classify_problems(self, problems):
        """

        Args:
            problems:

        Returns:

        """
        reminds, warnings = {}, {}
        for k, p in problems.items():
            p = self._classify(p)
            severity = p.severity
            if severity == 'remind':
                reminds[p.alarm_id] = p
            else:
                warnings[p.alarm_id] = p
        return reminds, warnings

    @staticmethod
    def _load_classification_criteria():
        data = CMDBService().select('alarm_classification')
        lst = data['data']['info']
        mapping = {}
        for item in lst:
            k = item['alarm_type']
            if k not in mapping:
                mapping[k] = []
            mapping[k].append(item)
        return mapping

    def __call__(self, problems):
        format_ps = {}
        for k, p in problems.items():
            p = self._classify(p)
            format_ps[k] = p
        return format_ps

    def _classify(self, p):
        if p.alarm_source == 'zabbix':
            return self._classify_zabbix_alarm(p)
        if p.alarm_source == 'spider':
            return self._classify_spider_alarm(p)
        return p

    def _classify_zabbix_alarm(self, p):
        for criterion in self.classification_criteria['zabbix']:
            if criterion['ignore_monitor_item_name'] and criterion['regex_string'] in p.alarm_info:
                p.severity = criterion['classification']
                return p
            else:
                if p.hostname == criterion['monitor_item_name'] and criterion['regex_string'] in p.alarm_info:
                    p.severity = criterion['classification']
                    return p
        return p

    def _classify_spider_alarm(self, p):
        for criterion in self.classification_criteria['spider']:
            if criterion['ignore_monitor_item_name'] and criterion['regex_string'] in p.alarm_info:
                p.severity = criterion['classification']
                return p
            else:
                if p.hostname == criterion['monitor_item_name'] and criterion['regex_string'] in p.alarm_info:
                    p.severity = criterion['classification']
                    return p
        return p


AlarmClassifier()
